package com.atguigu.spring.tx.service.impl;

import com.atguigu.spring.tx.bean.Account;
import com.atguigu.spring.tx.bean.Book;
import com.atguigu.spring.tx.dao.AccountDao;
import com.atguigu.spring.tx.dao.BookDAO;
import com.atguigu.spring.tx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.math.BigDecimal;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    AccountDao accountDao;

    @Autowired
    BookDAO bookDAO;

    @Override
    public boolean buyBook(int uid, int bid, int count) {
        Account account = accountDao.getAccountById(uid);
        System.out.println("before buy account:" + account);
        Book book = bookDAO.getBookById(bid);
        if (book == null) {
            System.out.println("book:" + bid + " is empty");
            return false;
        }
        System.out.println("before buy book:" + book);
        BigDecimal price = book.getPrice();
        BigDecimal custom = BigDecimal.valueOf((price.floatValue() * count));
        if (custom.compareTo(account.getBalance()) > 0) {
            System.out.println("balance:" + account.getBalance() + " less than count:" + custom);
            return false;
        }
        bookDAO.customStock(bid, count);
        accountDao.customBalance(uid, custom);
        book = bookDAO.getBookById(bid);
        if (null != book) {
            System.out.println("after buy book:" + book);
        } else {
            System.out.println("no more book");
        }
        account = accountDao.getAccountById(uid);
        System.out.println("after buy account:" + account);
        return true;
    }

    @Transactional
    @Override
    public void buyBookWithTx(int uid, int bid, int count) {
        Account account = accountDao.getAccountById(uid);
        System.out.println("before buy account:" + account);
        Book book = bookDAO.getBookById(bid);
        System.out.println("before buy book:" + book);
        BigDecimal price = book.getPrice();

        BigDecimal custom = price.multiply(BigDecimal.valueOf(count));
        if (custom.compareTo(account.getBalance()) > 0) {
            System.out.println("balance:" + account.getBalance() + " less than count:" + custom);
            return;
        }
        bookDAO.customStock(bid, count);
        accountDao.customBalance(uid, custom);
        book = bookDAO.getBookById(bid);
        System.out.println("after buy book:" + book);

        account = accountDao.getAccountById(uid);
        System.out.println("after buy account:" + account);

        int a = 10/(5+2-3-3-1);

    }
}
